package com.sxz.mall.mallauthserver.controller;

import com.alibaba.fastjson.JSON;
import com.sxz.mall.common.utils.HttpUtils;
import com.sxz.mall.common.utils.R;
import com.sxz.mall.mallauthserver.feign.MemberFeignService;
import com.sxz.mall.mallauthserver.vo.MemberVO;
import com.sxz.mall.mallauthserver.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    private MemberFeignService memberFeignService;

    /**
     * 授权回调接口地址，前端授权后的重定向接口地址
     * <p>
     * HttpSession：可以存储值到前端浏览器的 cookie值里面去（当前域名）
     * 但是看不懂，与存储的时候差异大
     *
     * @param code
     * @return
     */
    @RequestMapping("/oauth/weibo/success")
    public String weiboOAuth(String code, HttpSession session) throws Exception {

        // 根据code获取token，请求weibo接口
        Map<String, String> body = new HashMap<>();
        body.put("client_id", "111");
        body.put("client_secret", "abc");
        body.put("grant-type", "authorization_code");
        body.put("redirect_uri", "http:sxz.mall.com/oauth/weibo/success");
        body.put("code", code);

        // 发送请求
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com",
                "/oauth2/access_token",
                "post",
                new HashMap<>(),
                null,
                body);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            // token获取失败，表示登录授权失败，不应该成功登录
            return "redirect:http://sxz.auth.com/login.html";
        }

        // 获取到token和uid等信息
        String s = EntityUtils.toString(response.getEntity());
        SocialUser socialUser = JSON.parseObject(s, SocialUser.class);

        // 拿到socialUser之后，直接传入会员服务，进行登录的处理（注册或者登录）
        R r = memberFeignService.socialLogin(socialUser);
        if (r.getCode() != 0) {
            return "redirect:http://sxz.auth.com/login.html";
        }
        String entityJson = (String) r.get("entity");

        // 存入sessino，对应前端cookie里面存储有sessionid
        // SessionManager在统一管理，Map集合
        MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);

        // 添加了依赖和配置，会存储到redis中
        session.setAttribute("loginUser", memberVO);

        System.out.println("-----------entity" + entityJson);
        return "redirect:http://sxz.mall.com/";
    }
}
